<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="所属设备型号" prop="modelId">
        <el-select v-model="queryParams.modelId"
                   placeholder="请选择所属设备型号"
                   clearable
                   @keyup.enter.native="handleQuery">
          <el-option
            v-for="dict in deviceModelList"
            :key="dict.modelId"
            :label="dict.modelName"
            :value="dict.modelId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['app:deviceDocument:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['app:deviceDocument:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['app:deviceDocument:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceDocumentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="设备型号编号" align="center" prop="modelCode" />
      <el-table-column label="设备型号名称" align="center" prop="deviceModel.modelName"/>
      <el-table-column label="文件名称" align="center" prop="fileName"  min-width="180"  />
      <el-table-column label="文件类型" align="center" prop="fileType" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:deviceDocument:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备文档管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="所属设备型号" prop="modelId">
          <el-select v-model="form.modelId"
                     placeholder="请选择所属设备型号"
                     clearable>
            <el-option
              v-for="dict in deviceModelList"
              :key="dict.modelId"
              :label="dict.modelName"
              :value="dict.modelId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件上传">
        <div style="display: flex; align-content: flex-start; justify-content: flex-start">
          <div style="width: 350px;height: 100%">
            <el-upload
              ref="upload"
              :limit="fileLimit"
              accept=".pdf,.mp4"
              action=""
              :before-upload="handleBeforeUpload"
              :data="deployInfo"
              :headers="headers"
              :on-error="handleUploadError"
              :on-exceed="handleExceed"
              :on-success="handleUploadSuccess"
              :http-request="uploadOSS"
              class="upload-demo"
              :multiple="true"
              :show-file-list="true"
              :file-list="fileList"
              drag
            >
              <i class="el-icon-upload"/>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
              <div class="el-upload__tip text-center" slot="tip">
                <div class="el-upload__tip" slot="tip">
                  <div>
                    <el-progress :text-inside="true" :stroke-width="26" :percentage="percentageFile"
                                 status="success"></el-progress>
                  </div>
                </div>
                <div style="padding: 12px 0; text-align: left; color: red">只能上传pdf/mp4文件，且不超过500M</div>
              </div>
            </el-upload>
          </div>
        </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceDocument, getDeviceDocument, delDeviceDocument, addDeviceDocument, updateDeviceDocument } from "@/api/app/deviceDocument";
import { listDeviceModel} from "@/api/app/deviceModel";
import {getToken} from "@/utils/auth";
import {uploadFile} from "@/utils/miniooss";
export default {
  name: "DeviceDocument",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备文档管理表格数据
      deviceDocumentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelId: null,
        modelCode: null,
        fileName: null,
        fileType: null,
        fileUrl: null,
        createTime: null,
        updateTime: null
      },
      deviceModelList: [],
      // 表单参数
      form: {},
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileType: ["pdf", "mp4"],
      fileSize: 500,
      fileLimit: 10,
      percentageFile: 0,
      deployInfo: {},
      fileList: [],
      // 表单校验
      rules: {
        modelId: [
          { required: true, message: "设备型号id不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDeviceModels();
  },
  methods: {
    /** 查询设备文档管理列表 */
    getList() {
      this.loading = true;
      listDeviceDocument(this.queryParams).then(response => {
        this.deviceDocumentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDeviceModels() {
      listDeviceModel({
        pageNum: 1,
        pageSize: 100000
      }).then(response => {
        this.deviceModelList = response.rows;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        modelId: null,
        fileList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.documentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备文档管理";
      this.fileList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const documentId = row.documentId || this.ids
      getDeviceDocument(documentId).then(response => {
        this.form = response.data;
        this.fileList = {
          name: response.data.fileName,
          url: response.data.fileUrl,
          fileName: response.data.fileName,
          fileType: response.data.fileType,
          fileUrl: response.data.fileUrl
        }
        this.open = true;
        this.title = "修改设备文档管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.modelId == null){
            this.$modal.msgError("请选择所属设备型号");
            return;
          }else if (this.fileList.length == null || this.fileList.length === 0){
            this.$modal.msgError("请上传文档");
            return;
          }
          this.form.fileList = this.fileList
          if (this.form.documentId != null) {
            updateDeviceDocument(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeviceDocument(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const documentIds = row.documentId || this.ids;
      this.$modal.confirm('是否确认删除设备文档管理编号为"' + documentIds + '"的数据项？').then(function() {
        return delDeviceDocument(documentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/deviceDocument/export', {
        ...this.queryParams
      }, `deviceDocument_${new Date().getTime()}.xlsx`)
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$modal.closeLoading();
        this.$modal.msgSuccess("文件上传成功~~~~");
        let fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        let fileName = file.name.slice(0,file.name.indexOf("."))
      if (res.url.indexOf('?') > -1){
        res.url = res.url.slice(0,res.url.indexOf("?"));
      }
        this.fileList.push({
          name: fileName,
          fileName: fileName,
          fileType: fileExtension,
          fileUrl: res.url,
          url: res.url
        });
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      let fileExtension = "";
      if (this.fileType) {
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        let isTypeOk = false;
        this.fileType.forEach((type) => {
            if(fileExtension && fileExtension.indexOf(type) > -1) {
                  isTypeOk = true;

            }
        })
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.fileLimit} 个!`);
    },
    // 监听上传失败
    handleUploadError(e, file, fileList) {
      this.$modal.closeLoading()
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    },
    uploadOSS(file) {
      const _this = this;
      uploadFile(file.file, error => {
        console.log(error)
        this.handleUploadError()
      }, success => {
        console.log(success)
        if (success && success.url) {
          this.handleUploadSuccess(success,file.file)
        }
      }, process => {
        process = process.toString().replaceAll("%", '');
        process = parseInt(process);
        this.percentageFile = process;
        console.log(process)
      })
    },
  }
};
</script>
